<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/26
 * Time: 15:13
 */

namespace app\index\server;


use app\index\model\Product as ProductModel;
use app\index\model\ProductInfo as ProductInfoModel;
use app\lib\exception\DatabaseException;
use think\Db;
use think\Exception;

class ProductInfoServer extends BaseServer
{
    public function getList($params = [])
    {
        $params = $this->prep_param($params);
        try {
            // 总条数
            $count = ProductInfoModel::count();
            $list = ProductInfoModel::with(['product'])
                ->order($params['sort'], $params['order'])
                ->limit($params['offset'], $params['limit'])
                ->select();
        } catch (Exception $e) {
            // 有些问题 应该抛出错误异常
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return bootstrap_table_return($count, $list);
    }

    public function addOrUpdate($params = [])
    {
        // 判断商品是否存在
        $exists_product = $this->product_exists($params['name']);
        if(!$exists_product) {
            return setMsg(0, '您输入的商品不存在');
        }
        // 图片的处理
        $img_res = $this->handle_image($params['alias'], $params['url'], 'productinfo', isset($params['primary_key']));
        if($img_res['status'] == 0) {
            return setMsg(0, $img_res['msg']);
        }
        // 数据的准备
        $prep_data = [
            'product_id' => $exists_product->id,
            'price' => $params['price'],
            'member_price' => $params['member_price'],
            'purchase_price' => $params['purchase_price'],
            'stock' => $params['stock'],
            'color' => $params['color'],
            'size' => $params['size'],
            'is_home' => $params['is_home'],
            'status' => $params['status'],
            'wtcdtp' => $params['wtcdtp'],
            'hmkcbc' => $params['hmkcbc'],
            'floorprice' => $params['floorprice'],
            'url' => $img_res['msg'],
            'description' => $params['description'],
            'img_id' => $img_res['img_id'],
	   'name' => $params['name'] . '-' . $params['color']
        ];
        // 注意一下当主推为 1 时需要先把其他的都改为0 主推保持一个商品只有一个
        $count_own_product = ProductInfoModel::where('product_id', '=', $exists_product->id)
            ->count();
        Db::startTrans();
        if(($count_own_product >= 2) && $params['is_home']) {
            // 改变所有此类商品的状态
            ProductInfoModel::where('product_id', '=',  $exists_product->id)
                ->update(['is_home' => 0]);
        }
        // 插入这个值
        if(isset($params['primary_key'])) {
            $result = ProductInfoModel::where('id', '=', $params['primary_key'])
                ->update($prep_data);
        } else {
            $result = ProductInfoModel::insert($prep_data);
        }
        if($result) {
            Db::commit();
            return setMsg(1, '商品操作成功');
        }
        return setMsg(0, '商品操作失败');
    }

    public function detail($id)
    {
        try{
            $result = ProductInfoModel::with(['product', 'img'])
                ->where('id', '=', $id)
                ->find();
            if(!$result) {
                return setMsg(0, '没有找到此商品');
            }
        }catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '查找成功', $result);
    }

    public function changeStatus($id)
    {
        try {
            $info = ProductInfoModel::where('id', $id)
                ->find();
            $info->status = abs(($info->status) - 1);
            $result = $info->save();
            if(!$result) {
                return setMsg(0, '修改此商品状态失败');
            }
        }catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '修改此商品 状态成功');
    }
}